<?php

namespace catchAdmin\archives\service;

use app\common\lib\ZhyxMongo;
use app\common\model\CollectCase as CollectCaseModel;
use app\common\model\CollectClass as CollectClassModel;
use app\common\model\PatientInfo;
use MongoDB\BSON\ObjectId;

class CollectService
{
    /**
     * 关注方法
     * @param $id
     */
    public function followOperate($id)
    {
        $row = (new CollectCaseModel)->where('id', $id)->field('attention')->find()->toArray();

        if (isset($row['attention'])) {
            //判断当前用户是否存在关注
            if (in_array(request()->user()->id, $row['attention'])) {
                $arr = [];
                foreach ($row['attention'] as $key => $val) {
                    if ($val == request()->user()->id) {
                        unset($row['attention'][$key]);
                    }
                }
                $data['attention'] = $arr;
                krsort($data['attention']);
            } else {
                $data['attention'] = $row['attention'];
                $data['attention'][] = request()->user()->id;
            }
        } else {
            $data['attention'][] = request()->user()->id;
        }

        return (new CollectCaseModel)->saveData($id, $data);
    }

    /**
     * @param array $data
     * @return bool
     */
    public function monitor(array $data): bool
    {
        foreach ($data["patient_list"] as $k => &$v) {
            $v = new ObjectId($v);
        }

        $result = (new PatientInfo())->where("_id", "in", $data["patient_list"])->update([
            'monitor' => $data['target']??[],
            'is_setting_monitor' => true
        ]);
        return $result !== false;
    }

    public function cancelMonitor(array $data): bool
    {
        foreach ($data["patient_list"] as $k => &$v) {
            $v = new ObjectId($v);
        }

        $result = ZhyxMongo::getInstance()->setCollection('patient_info')->updateMany(["_id" => ['$in' => $data["patient_list"]]], [
            '$unset' => ['monitor' => 1],
            '$set' => ['is_setting_monitor' => false]
        ]);
        return $result->getMatchedCount() > 0;
    }

    /**
     * 添加收案分类
     * @param array $data
     * @retrun int
     */
    public function addCollectClass(array $data): int
    {
        //父级分类
        $data['department_id'] = request()->user()->department_id;
        if (!isset($data['parent_id']) || empty($data['parent_id'])) {
            $data['id'] = new ObjectId();
            $data['parent_id'] = 0;
            $data['xpath'] = "0-" . $data["id"];
        } else {
            //给父级的xpath查出来
            $result = (new CollectClassModel())->where('id', $data['parent_id'])->field('xpath')->find();
            $data['id'] = new ObjectId();
            $data['xpath'] = $result["xpath"] . '-' . $data['id'];
        }
        $data["type"] = (int)($data["type"] ?? 1);
        return (new CollectClassModel())->addData($data);
    }
}
